﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace XKJ.OAWeb.Infrastructrue.Helpers.JWT
{
    public class JWTHelper
    {
        private readonly JWTTokenOptions _tokenOptions;
        public JWTHelper(IOptions<JWTTokenOptions> tokenOptions)
        {
            _tokenOptions = tokenOptions.Value;
        }

        public string CreateToken(List<Claim> claims)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenOptions.SigningCredentials));
            //对秘钥加密
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //过期时间（秒）
            DateTime expires = DateTime.Now.AddSeconds(_tokenOptions.Expires);//两个小时
                                                                 //实例化JWT安全令牌对象
            var jwtToken = new JwtSecurityToken(

                issuer: _tokenOptions.Issuer,                   //发布者
                audience: _tokenOptions.Audience,                 //受众（发布给谁用）
                claims: claims,                  //发起人  订阅者   
                expires: expires,                //过期时间
                signingCredentials: credentials  //秘钥
                );
            //序列化jwt令牌从而得到一个字符串
            string strToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return strToken;
        }
    }
}
